package com.hammer.m3u8downloader;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.hammer.m3u8downloader.entity.M3U8DownloadItemEntity;
import com.hammer.m3u8downloader.util.LocalM3U8Manager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jaygoo.library.m3u8downloader.M3U8Downloader;
import jaygoo.library.m3u8downloader.OnM3U8DownloadListener;
import jaygoo.library.m3u8downloader.bean.M3U8Task;

public class M3U8Service extends Service {
    private List<M3U8DownloadItemEntity> downloadItemEntityList = new ArrayList<>();
    private OnM3U8DownloadListener onM3U8DownloadListener;
    private OnTaskListChangedListener onTaskListChangedListener;
    private Handler handler = new Handler();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e("info", "onBind");
        setListener();
        if (intent.getStringExtra("taskName") != null && intent.getStringExtra("taskUrl") != null) {
            addTask(intent.getStringExtra("taskName"), intent.getStringExtra("taskUrl"));
        }
        startTask();
        return new M3U8Binder();
    }

    public void addTask(String taskName, String taskUrl) {
        String m3u8Path = M3U8Downloader.getInstance().getM3U8Path(taskUrl);
        LocalM3U8Manager.getInstance(getApplicationContext()).addTask(taskName, taskUrl, m3u8Path, 0, 4);
        M3U8Downloader.getInstance().download(taskUrl);
        Toast.makeText(this, "新任务已添加", Toast.LENGTH_SHORT).show();
    }

    private void startTask() {
        downloadItemEntityList.clear();
        downloadItemEntityList.addAll(LocalM3U8Manager.getInstance(getApplicationContext()).getTaskList("<>2"));

        handler.removeCallbacks(runnable);
        handler.post(runnable);

    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (onTaskListChangedListener != null) {
                List<M3U8DownloadItemEntity> local = LocalM3U8Manager.getInstance(getApplicationContext()).getTaskList("<>2");
                if (downloadItemEntityList.size() != local.size()) {
                    downloadItemEntityList.clear();
                    downloadItemEntityList.addAll(local);
                    Log.e("local", "run: " + local.size());
                    onTaskListChangedListener.onTaskListChange(local);
                }
            }

            if (downloadItemEntityList.size() <= 0) {
                handler.removeCallbacks(this);
                stopForeground(true);
                stopSelf();
            }
            handler.postDelayed(this, 800);
        }
    };

    private void setListener() {
        M3U8Downloader.getInstance().setOnM3U8DownloadListener(new OnM3U8DownloadListener() {
            @Override
            public void onDownloadItem(M3U8Task task, long itemFileSize, int totalTs, int curTs) {
                super.onDownloadItem(task, itemFileSize, totalTs, curTs);
                Log.e("info", "onDownloadItem: " + itemFileSize + "|" + totalTs + "|" + curTs);
                if (onM3U8DownloadListener != null) {
                    onM3U8DownloadListener.onDownloadItem(task, itemFileSize, totalTs, curTs);
                }
            }

            @Override
            public void onDownloadSuccess(M3U8Task task) {
                super.onDownloadSuccess(task);
                LocalM3U8Manager.getInstance(getApplicationContext()).updateTaskInfo(task.getUrl(), 100, 2, task.getFormatTotalSize());
                int local = LocalM3U8Manager.getInstance(getApplicationContext()).getTaskList("<>2").size();
                int servi = downloadItemEntityList.size();
                Log.e("local", "onDownloadSuccess: 状态已更新-> 完成 -> local= " + local + " ; service=" + servi);
                if (onM3U8DownloadListener != null) {
                    onM3U8DownloadListener.onDownloadSuccess(task);
                }
                if (downloadItemEntityList.size() > 0) {
                    if (!M3U8Downloader.getInstance().isRunning()) {
                        M3U8Downloader.getInstance().download(downloadItemEntityList.get(0).getTaskUrl());
                    }
                }
                // stopForeground(true);
            }

            @Override
            public void onDownloadPause(M3U8Task task) {
                super.onDownloadPause(task);
                int local = LocalM3U8Manager.getInstance(getApplicationContext()).getTaskList("<>2").size();
                int servi = downloadItemEntityList.size();
                int currentStatus = LocalM3U8Manager.getInstance(getApplicationContext()).getTaskStatus(task.getUrl());
                Log.e("local", "onDownloadPause: currentStatus=" + currentStatus);
                if (currentStatus != 2) {
                    Log.e("local", "onDownloadPause: 状态已更新-> 暂停 -> local= " + local + " ; service=" + servi);
                    LocalM3U8Manager.getInstance(getApplicationContext()).updateTaskInfo(task.getUrl(), (int) (task.getProgress() * 100), 3, "0 kb");
                    if (onM3U8DownloadListener != null) {
                        onM3U8DownloadListener.onDownloadPause(task);
                    }
                }
                // stopForeground(true);
            }

            @Override
            public void onDownloadPending(M3U8Task task) {
                super.onDownloadPending(task);
                LocalM3U8Manager.getInstance(getApplicationContext()).updateTaskInfo(task.getUrl(), 0, 4, "0 kb");
                if (onM3U8DownloadListener != null) {
                    onM3U8DownloadListener.onDownloadPending(task);
                }
            }

            @Override
            public void onDownloadProgress(M3U8Task task) {
                super.onDownloadProgress(task);
                LocalM3U8Manager.getInstance(getApplicationContext()).updateTaskInfo(task.getUrl(), (int) (task.getProgress() * 100), 1, "0 kb");
                if (onM3U8DownloadListener != null) {
                    onM3U8DownloadListener.onDownloadProgress(task);
                }
                showNofication("正在下载" , (int) (task.getProgress() * 100), false);
            }

            @Override
            public void onDownloadPrepare(M3U8Task task) {
                super.onDownloadPrepare(task);
                LocalM3U8Manager.getInstance(getApplicationContext()).updateTaskInfo(task.getUrl(), (int) (task.getProgress() * 100), 6, "0 kb");
                if (onM3U8DownloadListener != null) {
                    onM3U8DownloadListener.onDownloadPrepare(task);
                }
                showNofication("准备下载", (int) (task.getProgress() * 100), true);
            }

            @Override
            public void onDownloadError(M3U8Task task, Throwable errorMsg) {
                super.onDownloadError(task, errorMsg);
                LocalM3U8Manager.getInstance(getApplicationContext()).updateTaskInfo(task.getUrl(), (int) (task.getProgress() * 100), 5, "0 kb");
                if (onM3U8DownloadListener != null) {
                    onM3U8DownloadListener.onDownloadError(task, errorMsg);
                }
                // stopForeground(true);
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


    public class M3U8Binder extends Binder {
        public M3U8Service getM3U8Service() {
            return M3U8Service.this;
        }
    }


    public void setOnM3U8DownloadListener(OnM3U8DownloadListener onM3U8DownloadListener) {
        this.onM3U8DownloadListener = onM3U8DownloadListener;

    }

    public void setOnTaskListChangedListener(OnTaskListChangedListener onTaskListChangedListener) {
        this.onTaskListChangedListener = onTaskListChangedListener;
    }

    private void showNofication(String content, int progress, boolean indeter) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            builder = new Notification.Builder(this, "m3u8_download_service");
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(new NotificationChannel("m3u8_download_service", "M3U8后台缓存服务", NotificationManager.IMPORTANCE_MIN));
            }
        } else {
            builder = new Notification.Builder(this);
        }
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round));
        builder.setContentTitle("M3U8后台缓存服务正在运行");
        builder.setContentText(content);
        builder.setOngoing(true);
        builder.setProgress(100, progress, indeter);
        Intent intent = new Intent(this, MainActivity.class);
        builder.setContentIntent(PendingIntent.getActivity(this, 0, intent, 0));
        startForeground(1, builder.build());
    }


    public interface OnTaskListChangedListener {
        void onTaskListChange(List<M3U8DownloadItemEntity> downloadItemEntityList);
    }

}
